package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 统计指定时间区域内获取营业额
     */
    public TurnoverReportVO getTurnoverReport(LocalDate begin, LocalDate end) {
        //获取每天begin和end日期
        List<LocalDate> localDateList=new ArrayList();
        localDateList.add(begin);
        while(!end.equals(begin)){
            begin=begin.plusDays(1);
            localDateList.add(begin);
        }
        //获取每天营业额
        List<Double> turnoverlist = new ArrayList();
        for (LocalDate date : localDateList) {
            //获取每天时间区域
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //调用mapper
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover =turnover==null ? 0.0 : turnover;
            turnoverlist.add(turnover);
        }
        //封装数据
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(localDateList, ","))
                .turnoverList(StringUtils.join(turnoverlist, ","))
                .build();

        return turnoverReportVO;
    }

    //统计指定时间区域内获取用户数据
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //获取每天begin和end日期
        List<LocalDate> localDateList=new ArrayList();
        localDateList.add(begin);
        while(!end.equals(begin)){
            begin=begin.plusDays(1);
            localDateList.add(begin);
        }

        //获取每天新增用户
        List<Integer> newUserList = new ArrayList();
        //获取每天总用户
        List<Integer> totalUserList = new ArrayList();
        for (LocalDate localDate : localDateList) {
            //获取每天时间区域
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end",endTime);

            Integer totalUser= userMapper.countByMap(map);
            map.put("begin",beginTime);

            Integer newUser= userMapper.countByMap(map);
            newUserList.add(newUser);

            totalUserList.add(totalUser);
        }



        return UserReportVO.builder()
                .dateList(StringUtils.join(localDateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 订单统计
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //获取每天begin和end日期
        List<LocalDate> localDateList=new ArrayList();
        localDateList.add(begin);
        while(!end.equals(begin)){
            begin=begin.plusDays(1);
            localDateList.add(begin);
        }

        //每日订单数
        List<Integer> orderNumber=new ArrayList();
        //每日有效订单数
        List<Integer> validOrder=new ArrayList();
        for (LocalDate date : localDateList) {
            //获取每天时间区域
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);

            Integer orderCount= orderMapper.countByMap(map);
            orderNumber.add(orderCount);
            //有效订单数
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount= orderMapper.countByMap(map);
            validOrder.add(validOrderCount);
        }
        //计算时间区域内的订单总数
        Integer totalOrderNumber = orderNumber.stream().reduce(Integer::sum).get();
        //计算时间区域内的有效订单数
        Integer validOrderNumber = validOrder.stream().reduce(Integer::sum).get();

        //计算订单完成率
        double orderCompletionRate = totalOrderNumber==0 ? 0.0:(double) validOrderNumber / totalOrderNumber;

        return OrderReportVO.builder()
                .dateList(StringUtils.join(localDateList,","))
                .orderCountList(StringUtils.join(orderNumber,","))
                .validOrderCountList(StringUtils.join(validOrder,","))
                .totalOrderCount(totalOrderNumber)
                .validOrderCount(validOrderNumber)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排行榜前10
     */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        //获取每天时间区域
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getTop10(beginTime, endTime);
        List<String> names = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());



        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names,","))
                .numberList(StringUtils.join(numbers,","))
                .build();
    }

    /**
     * 数据导出
     * @param response
     */
    public void export(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        //查询概览运营数据，提供给excel模板文件
        BusinessDataVO businessData= workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));
        InputStream inpoutStream =this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try{
            //基于提供好的模板文件创建一个新的excel表格对象
            XSSFWorkbook workbook =new XSSFWorkbook(inpoutStream);
            //获得excel文件的一个sheet页
            XSSFSheet sheet =workbook.getSheet("sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间: "+begin+"至"+end+"     ");

            //获取第四行
            XSSFRow row =sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row =sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30 ; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                BusinessDataVO businessDataDetail = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataDetail.getTurnover());
                row.getCell(3).setCellValue(businessDataDetail.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataDetail.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataDetail.getUnitPrice());
                row.getCell(6).setCellValue(businessDataDetail.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            //关闭资源
            out.flush();
            out.close();
            workbook.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
